/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.kj.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.common.lang.ObjectUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mapper.JsonMapper;
import com.jeesite.common.shiro.cache.K;
import com.jeesite.modules.aliyun.msg.AliyunSmsUtils;
import com.jeesite.modules.kj.entity.KjActivityJob;
import com.jeesite.modules.kj.entity.KjMemberJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.kj.entity.KjActivity;
import com.jeesite.modules.kj.dao.KjActivityDao;
import com.jeesite.modules.file.utils.FileUploadUtils;

/**
 * kj_activityService
 * @author hzy
 * @version 2021-07-06
 */
@Service
@Transactional(readOnly=true)
public class KjActivityService extends CrudService<KjActivityDao, KjActivity> {

	@Value("${msg.sms.template.qrCodeUpload}")
	private String qrcodeUploadTpl;
	@Autowired
	KjActivityJobService kjActivityJobService;

	@Autowired
	KjMemberJobService kjMemberJobService;
	/**
	 * 获取单条数据
	 * @param kjActivity
	 * @return
	 */
	@Override
	public KjActivity get(KjActivity kjActivity) {
		return super.get(kjActivity);
	}

	/**
	 * 查询分页数据
	 * @param kjActivity 查询条件
	 * @return
	 */
	@Override
	public Page<KjActivity> findPage(KjActivity kjActivity) {
		return super.findPage(kjActivity);
	}

	/**
	 * 保存数据（插入或更新）
	 * @param kjActivity
	 */
	@Override
	@Transactional(readOnly=false)
	public void save(KjActivity kjActivity) {

		super.save(kjActivity);

		// 保存上传图片
		FileUploadUtils.saveFileUpload(kjActivity.getId(), "kjActivity_image");
	}

	/**
	 * 保存数据（插入或更新）
	 * @param kjActivity
	 */
	@Transactional(readOnly=false)
	public void saveForm(KjActivity kjActivity) {

		super.save(kjActivity);
		KjActivityJob where = new KjActivityJob();
		where.setActivityId(kjActivity.getId());
		List<KjActivityJob> jobs = kjActivityJobService.findList(where);
		//删除前端已删除的
		jobs.forEach(job -> {
			boolean includeAd = false;
			for (KjActivityJob j : kjActivity.getActivityJobList()) {
				if(j.getId() != null && j.getId().equals(job.getId())){
					includeAd = true;
					KjMemberJob kjMemberJob=new KjMemberJob();
					kjMemberJob.setActivityId(j.getActivityId());
					kjMemberJob.setJobId(j.getId());
					List<KjMemberJob> list=kjMemberJobService.findList(kjMemberJob);
					for(KjMemberJob kjob:list ){
						kjob.setJobName(j.getJobName());
						kjMemberJobService.update(kjob);
					}
				}
			}
			if(!includeAd){
				KjMemberJob memberJob=new KjMemberJob();
				memberJob.setJobId(job.getId());
				memberJob.setActivityId(kjActivity.getId());
				for(KjMemberJob kjMemberJob: kjMemberJobService.findList(memberJob)) {
					kjMemberJobService.delete(kjMemberJob);
				}
				kjActivityJobService.delete(job);
			}
		});
		if(kjActivity.getActivityJobList().size() > 0){
			kjActivity.getActivityJobList().forEach(job -> {
				job.setActivityId(kjActivity.getId());
				job.setActivityName(kjActivity.getName());

				if(StringUtils.isBlank(job.getId())) {
					job.setId(IdGen.nextId());
					kjActivityJobService.insert(job);
				}else {
					kjActivityJobService.update(job);
				}
					});
		}

		// 保存上传图片
		FileUploadUtils.saveFileUpload(kjActivity.getId(), "kjActivity_image");
	}

	/**
	 * 更新状态
	 * @param kjActivity
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(KjActivity kjActivity) {
		super.updateStatus(kjActivity);
	}

	/**
	 * 删除数据
	 * @param kjActivity
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(KjActivity kjActivity) {
		super.delete(kjActivity);
	}

	@Transactional(readOnly=false)
	public void autoStartActivity(){
		dao.autoStartActivity();
	}

	@Transactional(readOnly=false)
	public void autoSignStartActivity(){
		dao.autoSignStartActivity();
	}

	@Transactional(readOnly=false)
	public void autoSignEndActivity(){
		dao.autoSignEndActivity();
	}

	@Transactional(readOnly=false)
	public void autoEndActivity(){
		dao.autoEndActivity();
	}


	public String validDate(KjActivity activity){
		//bugID: 4377 需求变更
		if(activity.getSignEndTime().compareTo(activity.getSignStartTime()) < 0){
			return "活动报名开始时间必须小于活动报名结束时间";
		}
		if(activity.getEndTime().compareTo(activity.getStartTime()) < 0){
			return "活动开始时间必须小于活动结束时间";
		}

//		if(activity.getStartTime().compareTo(activity.getSignEndTime()) < 0){
//			return "活动开始时间必须大于活动报名结束时间";
//		}

		return null;
	}

	public void sendQrcodeUploadSms(KjActivity activity){
		KjMemberJob where = new KjMemberJob();
		where.setActivityId(activity.getId());
		where.setApproveStatus(KjMemberJob.OK);
		List<KjMemberJob> memberJobs = kjMemberJobService.findList(where);
		for (KjMemberJob mj: memberJobs
			 ) {
			if(mj.getKjMember() != null) {
				authSms(mj.getKjMember().getMobile(), qrcodeUploadTpl);
			}
		}
	}

	public void authSms(String mobile, String tpl){
		Map<String, Object> tplData = new HashMap<>();
		String result = AliyunSmsUtils.sendByTemplate(mobile, tpl, JSON.toJSONString(tplData));
		Map<String, Object> map = JsonMapper.fromJson(result, Map.class);
		// 发送成功
		if (ObjectUtils.toInteger(map.get("result")) == 0){
		}//			 发送失败
		else{
			logger.error(text("短信发送失败{0}", result));
		}
	}
}
